//创建用户相关的仓库
import { defineStore } from "pinia";
//引入接口
import { reqLogin } from "@/api/user";
//引入数据类型
import type { loginForm, loginResult } from "@/api/user/type";
import type { UserState } from "./types/type";
//引入存储与读取token的方法
import { SET_TOKEN, GET_TOKEN } from "@/utils/token";
const useUserStore = defineStore("User", {
  //定义状态
  state(): UserState {
    return {
      token: GET_TOKEN(), //用户token
    };
  },
  //异步|同步修改状态
  actions: {
    //用户登录的方法
    async userLogin(data: loginForm) {
      //登录请求
      const result: loginResult = await reqLogin(data);
      //登录请求：成功返回200->token
      if (result.code === 200) {
        this.token = (result.data.token as string) || "";
        //将token存储到本地
        // localStorage.setItem("token", (result.data.token as string) || "");
        SET_TOKEN(result.data.token as string);

        return "请求成功";
      } else {
        //失败返回400->错误信息
        return Promise.reject(new Error(result.data.message));
      }

      console.log(result);
    },
  },
  //计算属性
  getters: {},
});

//导出用户仓库
export { useUserStore };
